#include<iostream>
#include<cstdlib>
#include<unistd.h> 


//获取请求数据
bool GetQueryString(std::string& query_string)
{ 
  std::string method = getenv("METHOD");
  bool result = false; 
  if("GET" == method)
  {
    query_string = getenv("QUERY_STRING");
    result = true;
  }
  else if("POST" == method)
  {
    int content_length = atoi(getenv("CONTENT_LENGTH"));
    //读数据
    char ch;
    while(content_length)
    {
      read(0,&ch,1); //读取一个字节
      query_string += ch;
      content_length--;
    } 
    result = true;
  } else 
  {
    result = false;
  }
  return result;
}


void CutString(std::string& in ,std::string sep , std::string& out1 , std::string& out2)
{
  size_t pos = in.find(sep);
  if(pos != std::string::npos) 
  {
    //找到了
    out1 = in.substr(0,pos);
    out2 = in.substr(pos+sep.size());
  }
}


int main()
{
  std::string query_string;
  GetQueryString(query_string); 

  //a=100&b=200 拆分成 a=100 和 b=200
  std::string str1;
  std::string str2;
  CutString(query_string , "&" , str1 , str2);

  std::string name1 ;
  std::string name2 ;
  std::string value1 ;
  std::string value2 ;

  //a=100 拆分成 a 和 100
  CutString(str1,"=",name1, value1); 
  
  //a=100 拆分成 a 和 100
  CutString(str2,"=",name2, value2); 
 
  //重定向
  std::cout << name1  << ":"  <<  value1 << std::endl ; 
  std::cout << name2  << ":"  <<  value2 << std::endl ; 
  
  //输出到显示器
  std::cerr << name1  << ":"  <<  value1 << std::endl ; 
  std::cerr << name2  << ":"  <<  value2 << std::endl ; 

  return 0;
}
